import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'package:drm/util/SpUtils.dart';
import 'package:drm/base/user.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'package:drm/base_bloc/base_list_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';


abstract class BaseListPageState<B extends ListBloc, T,
    Page extends StatefulWidget> extends State<Page> {
  RefreshController _refreshController;
  B _bloc;

  int page = 1;
  User user;
  int total = 0;
  List<T> data = [];
  Widget _headView;
  Widget _footView;
  List<Widget> _mainItemView;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    user = SpUtils.getLocalUser();
    _refreshController = RefreshController();
    print('初始化bloc');
    _bloc = iniBloc();
    _onRefresh();
  }

  //获取ListBloc；
  B getBloc() {
    return _bloc;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    return Column(
      children: <Widget>[
        Container(
            child: SizedBox(
          height: 5,
        )),
        Expanded(child: iniMainView(context)),
      ],
    );
  }

  //中间视图；
  Widget iniMainView(BuildContext context) {
    return BlocBuilder(
        bloc: _bloc,
        builder: (context, state) {
          print(state.runtimeType);
          if (state is RefreshState) {
            print(state.isSuccess);
            if (state.isSuccess) {
              //获取列表数据成功；
              total = state.total;
              List<T> result = state.items;
              if (page == 1) {
                if (result == null || result.length == 0) {
                  result = [];
                }
                data = result;
                _refreshController.refreshCompleted();
              } else {
                if (result == null || result.length == 0) {
                  _refreshController.loadNoData();
                } else {
                  data.addAll(result);
                  _refreshController.loadComplete();
                }
              }
              if (data.length >= total) {
                _refreshController.loadNoData();
              }
            } else {
              data = null;
              _refreshController.refreshCompleted();
            }
//


            return SmartRefresher(
                enablePullDown: true,
                enablePullUp: true,
                header: ClassicHeader(),
                controller: _refreshController,
                onRefresh: _onRefresh,
                onLoading: _onLoading,
                child: ListView(
                  children:
                      iniListView(context, data, errorCode: state.message),
                ));
          }

          if (state is RefreshEvent) {
            refresh();
          }

          if (state is InitialListState) {

            return Center(
              child: Container(
                  height: 100,
                  width: 100,
                  child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        CircularProgressIndicator(),
                        SizedBox(
                          height: 10,
                        ),
                        Text(
                          '加载中...',
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: 14,
                              decoration: TextDecoration.none),
                        )
                      ])),
            );
          }
        });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    print('disponse');
    _refreshController.dispose();
    _bloc.dispose();
  }

  void _onRefresh() {
    page = 1;
    getBloc().dispatch(iniRefushEvent());
  }

  void _onLoading() {
    page = page + 1;
    getBloc().dispatch(iniRefushEvent());
  }

  toast(String msg) {
    Fluttertoast.showToast(
        msg: msg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Colors.black45,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  void refresh() {
    page = 1;

    getBloc().dispatch(iniRefushEvent());
//    _refreshController.requestRefresh();
  }

  //头部视图；
  Widget iniHeaderView(BuildContext context);

  //尾部视图；
  Widget inifootView(BuildContext context);

  //初始化Bloc；
  B iniBloc();

  //初始化刷新事件；
  RefreshListEvent<T> iniRefushEvent();

  // 数据获取成功后，进行的视图初始化；
  List<Widget> iniListItems(List<T> datas);

  List<Widget> iniListView(BuildContext context, List<T> datas,
      {String errorCode}) {
    _headView = iniHeaderView(context);
    _footView = inifootView(context);
    _mainItemView = iniMainItemView(datas, errorCode);
    List<Widget> items = [];
    if (_headView != null) {
      items.add(_headView);
    }
    if (_footView != null) {
      items.add(_footView);
    }
    if (_mainItemView != null && _mainItemView.length != 0) {
      items.addAll(_mainItemView);
    }
    return items;
  }

  List<Widget> iniMainItemView(List<T> datas, String errorCode) {
    if (datas == null) {
      return [
        Padding(
            padding: EdgeInsets.only(top: 200),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Text('$errorCode'),
                SizedBox(height: 10,),
                Text('请求出错，下拉重新尝试刷新'),
              ],
            ))
      ];
    }
    if (datas != null && data.length == 0) {
      return [
        Center(
          child: Text('没有获取到数据，下拉重新尝试刷新'),
        ),
      ];
    }

    return iniListItems(datas);
  }
}
